package personnal.blogprinter.htmlparser;

import java.io.StringReader;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.log4j.Logger;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import personnal.blogprinter.exceptions.GenerationException;

import com.lowagie.text.Document;

public class SaxHtmlParser {

    private static Logger logger = Logger.getLogger(SaxHtmlParser.class);

    private SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    private EntityResolver htmlEntityResolver = new HtmlEntityResolver();

    private XMLReader reader;

    public SaxHtmlParser() throws GenerationException {
        super();
        try {
            this.reader = createXmlReader();
        } catch (Exception e) {
            throw new GenerationException("Problem while creating HTML parser", e);
        }
    }

    public void parse(Document document, String content) throws GenerationException {
        logger.trace(content);
        try {
            SaxHtmlHandler saxHandler = new SaxHtmlHandler(document);
            saxHandler.setControlOpenClose(false);
            this.reader.setContentHandler(saxHandler);
            this.reader.setEntityResolver(this.htmlEntityResolver);
            this.reader.setErrorHandler(saxHandler);
            this.reader.setDTDHandler(saxHandler);
            InputSource is = new InputSource(new StringReader(content));
            this.reader.parse(is);
        } catch (Exception e) {
            throw new GenerationException("Problem while parsing HTML document", e);
        }
    }

    protected XMLReader createXmlReader() throws ParserConfigurationException, SAXException {
        this.parserFactory.setValidating(false);
        SAXParser parser = this.parserFactory.newSAXParser();
        return parser.getXMLReader();
    }
}
